package com.hengpeng.itfinoss.controller.article;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hengpeng.common.acl.vo.Passport;
import com.hengpeng.common.constant.Constant;
import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.QueryResult;
import com.hengpeng.common.persist.entity.AbstractEntity.BoolValue;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.persist.query.Projections;
import com.hengpeng.common.persist.query.constants.QueryConstants.QueryType;
import com.hengpeng.common.persist.query.model.Order.OrderType;
import com.hengpeng.common.util.CalendarUtil;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.common.web.tags.ListTag.Pagination;
import com.hengpeng.itfinbase.persist.Article;
import com.hengpeng.itfinbase.persist.ArticleCategory;
import com.hengpeng.itfinbase.persist.ArticleDiscuss;
import com.hengpeng.itfinbase.persist.ArticleDiscuss.DiscussState;
import com.hengpeng.itfinbase.persist.ArticleGroup;
import com.hengpeng.itfinbase.persist.ArticleGroupEx;
import com.hengpeng.itfinbase.persist.Attachment;
import com.hengpeng.itfinbase.persist.Attachment.AttachmentType;
import com.hengpeng.itfinbase.persist.SystemConfig;
import com.hengpeng.itfinoss.controller.BaseController;
import com.hengpeng.itfinoss.controller.vo.ArticleDiscussVo;
import com.hengpeng.itfinoss.controller.vo.ArticleVo;
import com.hengpeng.itfinoss.service.ServiceFactory;
import com.hengpeng.itfinoss.util.BeanClone;
import com.hengpeng.itfinoss.util.CollectionHelp;

/**
 * <pre>
 * 新闻控制类
 * </pre>
 * @author pengfangliang
 * @version 1.0, 2010-8-18
 */
@Controller
@RequestMapping("/am")
public class ArticleController extends BaseController
{
	final static Log logger = LogFactory.getLog(ArticleController.class);

	@Autowired
	private ServiceFactory serviceFactory;

	@RequestMapping(value = "/new", method = RequestMethod.GET)
	public ModelAndView preCreate()
	{
		// 获取所有文章类别，不进行多级划分后，parent字段处于闲置状态
		List<ArticleCategory> categorys = serviceFactory.getArticleCategorySerivce().findAll().getReturnValue();
		Article article = new Article();
		article.setIsAudited(BoolValue.YES);
		ModelAndView modelAndView = new ModelAndView("/article/detail");
		modelAndView.addObject("article", article);
		modelAndView.addObject("categorys", categorys);
		// 分组
		List<ArticleGroup> articleGroups = new ArrayList<ArticleGroup>();
		ArticleGroup articleGroup = new ArticleGroup();
		articleGroup.setId(-1L);
		articleGroup.setName("全部");
		articleGroups.add(articleGroup);
		articleGroups.addAll(serviceFactory.getPersistService().list(ArticleGroup.class));
		modelAndView.addObject("groups", articleGroups);
		return modelAndView;
	}

	@RequestMapping(method = RequestMethod.POST)
	public String add(HttpServletRequest request, String[] acticleGroups, ModelMap map)
	{
		String _setTopEndTime = request.getParameter("setTopEndTime");
		Date topEndTime = null;
		if (_setTopEndTime != null)
			topEndTime = CalendarUtil.parseFormatNoMM(_setTopEndTime);
		String content = request.getParameter("content");
		String clickRate = request.getParameter("clickRate");
		String url = request.getParameter("url");
		HttpSession session = request.getSession();
		Passport passport = (Passport) session.getAttribute(Constant.PROFILE_SESSION_NAME);
		Article model = new Article();
		model.setKeywords(request.getParameter("keywords"));
		model.setAppUserId(passport.getUserId());
		model.setRealName(passport.getRealName());
		model.setSetTopEndTime(topEndTime);
		// 点击率
		if (clickRate != null && !"".equals(clickRate.trim()))
		{
			model.setClickRate(Long.parseLong(clickRate));
		}
		else
		{
			model.setClickRate(0L);
		}

		// 头条新闻颜色
		model.setTitleColor(request.getParameter("titleColor"));

		// 作者
		String author = request.getParameter("author");
		// 自定义名称
		if ("-1".equals(author.trim()))
		{
			author = request.getParameter("author_self");
		}
		if (StringHelper.isEmpty(author))
		{
			author = passport.getNickName();
		}
		model.setAuthor(author);
		model.setCategory(serviceFactory.getPersistService().get(ArticleCategory.class,
				Long.parseLong(request.getParameter("category"))));
		model.setContent(content);
		Date now = new Date();
		model.setUpdateTime(now);
		// 发布时间
		String publishTime = request.getParameter("publishTime");
		if (StringHelper.isEmpty(publishTime))
		{
			model.setPublishTime(now);
		}
		else
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			try
			{
				model.setPublishTime(sdf.parse(publishTime));
			}
			catch (ParseException e)
			{
				logger.error(e);
				model.setPublishTime(now);
			}
		}
		model.setFullTitle(request.getParameter("fullTitle"));
		model.setIsHignlight(request.getParameter("isHignlight").equalsIgnoreCase("YES") ? BoolValue.YES : BoolValue.NO);
		model.setIsAudited(request.getParameter("isAudited").equalsIgnoreCase("YES") ? BoolValue.YES : BoolValue.NO);
		model.setIsTop(request.getParameter("isTop").equalsIgnoreCase("YES") ? BoolValue.YES : BoolValue.NO);
		model.setSource(request.getParameter("source"));
		model.setTitle(request.getParameter("title"));
		model.setVersion(Long.parseLong(request.getParameter("version")));
		try
		{
			ServiceResult<Article> result = serviceFactory.getArticleService().save(model);
			String indexImage = request.getParameter("indexImage");
			if (!StringHelper.isEmpty(indexImage))
			{
				String name = indexImage.substring(indexImage.lastIndexOf("/") + 1);
				String icon = indexImage.substring(0, indexImage.lastIndexOf("/") + 1) + "icon/" + name;
				Attachment attachment = new Attachment();
				attachment.setArticleId(result.getReturnValue().getId());
				attachment.setFilePath(indexImage);
				attachment.setIconPath(icon);
				attachment.setName(name);
				attachment.setUrl(url);
				attachment.setType(AttachmentType.IMAGE);
				serviceFactory.getPersistService().save(attachment);
			}
			// 分组
			if (acticleGroups != null)
			{
				List<ArticleGroupEx> articleGroupExs = new ArrayList<ArticleGroupEx>();
				ArticleGroupEx articleGroupEx = null;
				for (String groupIdTmp : acticleGroups)
				{
					if (groupIdTmp != null && !"".equals(groupIdTmp.trim()))
					{
						Long groupId = Long.parseLong(groupIdTmp);
						if (groupId != null)
						{
							articleGroupEx = new ArticleGroupEx();
							articleGroupEx.setArticleId(result.getReturnValue().getId());
							articleGroupEx.setGroupId(groupId);
							articleGroupExs.add(articleGroupEx);
						}
					}
				}
				serviceFactory.getPersistService().saveAllObject(articleGroupExs);
			}

			return returnSuccess(map, result, "/am/list");
		}
		catch (Exception ex)
		{
			logger.error(ex);
			return returnError(map, ex);
		}
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.POST)
	public String update(@PathVariable long id, String[] acticleGroups, HttpServletRequest request, ModelMap map)
	{
		String _setTopEndTime = request.getParameter("setTopEndTime");
		Date topEndTime = null;
		if (_setTopEndTime != null)
			topEndTime = CalendarUtil.parseFormatNoMM(_setTopEndTime);
		HttpSession session = request.getSession();
		Passport passport = (Passport) session.getAttribute(Constant.PROFILE_SESSION_NAME);
		Article model = serviceFactory.getPersistService().get(Article.class, id);
		model.setKeywords(request.getParameter("keywords"));

		// 头条新闻颜色
		model.setTitleColor(request.getParameter("titleColor"));

		// 作者
		String author = request.getParameter("author");
		// 自定义名称
		if ("-1".equals(author.trim()))
		{
			author = request.getParameter("author_self");
		}
		if (StringHelper.isEmpty(author))
		{
			author = passport.getNickName();
		}
		model.setAuthor(author);
		model.setRealName(passport.getRealName());
		model.setUpdateTime(new Date());
		model.setSetTopEndTime(topEndTime);
		model.setCategory(serviceFactory.getPersistService().get(ArticleCategory.class,
				Long.parseLong(request.getParameter("category"))));
		model.setContent(request.getParameter("content"));
		model.setUpdateTime(new Date());
		// 发布时间
		String publishTime = request.getParameter("publishTime");
		if (!StringHelper.isEmpty(publishTime))
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			try
			{
				model.setPublishTime(sdf.parse(publishTime));
			}
			catch (ParseException e)
			{
				logger.error(e);
			}
		}
		model.setFullTitle(request.getParameter("fullTitle"));
		model.setIsAudited(request.getParameter("isAudited").equalsIgnoreCase("YES") ? BoolValue.YES : BoolValue.NO);
		model.setIsHignlight(request.getParameter("isHignlight").equalsIgnoreCase("YES") ? BoolValue.YES : BoolValue.NO);
		model.setIsTop(request.getParameter("isTop").equalsIgnoreCase("YES") ? BoolValue.YES : BoolValue.NO);
		model.setSource(request.getParameter("source"));
		model.setTitle(request.getParameter("title"));
		model.setVersion(Long.parseLong(request.getParameter("version")));
		try
		{
			ServiceResult<Article> result = serviceFactory.getArticleService().modfiy(model);
			String indexImage = request.getParameter("indexImage");
			if (!StringHelper.isEmpty(indexImage))
			{
				String name = indexImage.substring(indexImage.lastIndexOf("/") + 1);
				String icon = indexImage.substring(0, indexImage.lastIndexOf("/") + 1) + "icon/" + name;
				serviceFactory.getArticleService().batchRemove("articleId",
						new Long[] { result.getReturnValue().getId() }, Attachment.class);
				Attachment attachment = new Attachment();
				attachment.setArticleId(result.getReturnValue().getId());
				attachment.setFilePath(indexImage);
				attachment.setIconPath(icon);
				attachment.setName(name);
				attachment.setType(AttachmentType.IMAGE);
				attachment.setUrl(request.getParameter("url"));
				serviceFactory.getPersistService().save(attachment);
			}

			// 分组
			if (acticleGroups != null)
			{
				List<ArticleGroupEx> articleGroupExs = new ArrayList<ArticleGroupEx>();
				ArticleGroupEx articleGroupEx = null;
				serviceFactory.getArticleService().batchRemove("articleId",
						new Long[] { result.getReturnValue().getId() }, ArticleGroupEx.class);
				for (String groupIdTmp : acticleGroups)
				{
					if (groupIdTmp != null && !"".equals(groupIdTmp.trim()))
					{
						Long groupId = Long.parseLong(groupIdTmp);
						if (groupId != null)
						{
							articleGroupEx = new ArticleGroupEx();
							articleGroupEx.setArticleId(result.getReturnValue().getId());
							articleGroupEx.setGroupId(groupId);
							articleGroupExs.add(articleGroupEx);
						}
					}
				}
				serviceFactory.getPersistService().saveAllObject(articleGroupExs);
			}

			return returnSuccess(map, result, "/am/list");
		}
		catch (Exception ex)
		{
			logger.error(ex);
			return returnError(map, ex);
		}

	}

	@RequestMapping(value = "/remove")
	public String delete(HttpServletRequest request, Long[] ids, ModelMap map)
	{
		if (ids == null || ids.length <= 0)
		{
			return returnError(map, "要删除的新闻ID不能为空！");
		}
		try
		{
			Set<Object> set = new HashSet<Object>(Arrays.asList(ids));
			ServiceResult<Article> result = serviceFactory.getArticleService().remove(set);
			serviceFactory.getArticleService().batchRemove("articleId", ids, ArticleGroupEx.class);
			serviceFactory.getArticleService().batchRemove("articleId", ids, Attachment.class);
			return returnSuccess(request, map, result, "/am/list");
		}
		catch (Exception ex)
		{
			logger.error(ex);
			return returnError(map, ex);
		}
	}

	@RequestMapping(value = "/list")
	public String list(ModelMap model, HttpServletRequest request, String id, String appUserId, String author,
			Long categoryId, String content, String fullTitle, BoolValue isAudited, BoolValue isHignlight,
			BoolValue isTop, String source, String updateTime1, String updateTime2, String setTopEndTime1,
			String setTopEndTime2)
	{

		Date updateTimeBegin = null;
		Date updateTimeEnd = null;
		Date setTopEndTimeBegin = null;
		Date setTopEndTimeEnd = null;
		ArticleCategory category = new ArticleCategory();

		if (updateTime1 != null && updateTime1.trim().length() > 0)
			updateTimeBegin = CalendarUtil.parseFormatNoMM(updateTime1);
		if (updateTime2 != null && updateTime2.trim().length() > 0)
			updateTimeEnd = CalendarUtil.parseFormatNoMM(updateTime2);
		if (setTopEndTime1 != null && setTopEndTime1.trim().length() > 0)
			setTopEndTimeBegin = CalendarUtil.parseFormatNoMM(setTopEndTime1);
		if (setTopEndTime2 != null && setTopEndTime2.trim().length() > 0)
			setTopEndTimeEnd = CalendarUtil.parseFormatNoMM(setTopEndTime2);
		if (categoryId != null && categoryId != 0L)
			category = serviceFactory.getArticleCategorySerivce().get(categoryId).getReturnValue();
		model.put("isTop", isTop);
		model.put("id", id);
		model.put("author", author);
		model.put("category", category);
		model.put("content", content);
		model.put("fullTitle", fullTitle);
		model.put("source", source);
		model.put("updateTime1", updateTime1);
		model.put("updateTime2", updateTime2);
		model.put("setTopEndTime1", setTopEndTime1);
		model.put("setTopEndTime2", setTopEndTime2);
		Pagination page = new Pagination(request);
		page.setPageSize(this.getPageSize(request));
		try
		{
			Set<ArticleCategory> categorys = serviceFactory.getArticleCategorySerivce()
					.findAllArticleCategorySort(null).getReturnValue();
			LinkedHashMap<String, OrderType> sortMap = new LinkedHashMap<String, OrderType>();
			sortMap.put("id", OrderType.DESC);
			id = StringHelper.isEmpty(id) ? "-1" : id;
			QueryResult<Article> result = serviceFactory.getArticleService().findArticle(Long.parseLong(id), null,
					author, findCategoryChildrenIds(categoryId), content, fullTitle, null, null, isTop, source,
					updateTimeBegin, updateTimeEnd, setTopEndTimeBegin, setTopEndTimeEnd, page.currentPage,
					page.pageSize, sortMap);
			List<Article> articles = result.getResults();
			List<ArticleVo> articleVos = new ArrayList<ArticleVo>();
			for (Article article : articles)
			{
				article.setFullTitle("(ID:" + article.getId() + ")" + article.getFullTitle());

				ArticleVo articleVo = BeanClone.clone(article, ArticleVo.class);
				DynamicQuery query = new DynamicQuery(ArticleDiscuss.class);
				query.eq("articleId", article.getId());
				query.eq("state", DiscussState.NOAUDIT);
				Long count = serviceFactory.getPersistService().findPageCount(query, "id");
				articleVo.setNotAuditCount(count);
				articleVo.setAuditUrl("discuss_" + article.getId());
				
				
				DynamicQuery groupquery = new DynamicQuery(ArticleGroup.class , "g");
				groupquery.createAlias(ArticleGroupEx.class, "ge");
				groupquery.addProjection(Projections.property("g.*"));
				groupquery.eqProperty("g.id", "ge.groupId");
				groupquery.eq("ge.articleId", article.getId());
				groupquery.setQueryType(QueryType.JDBC);
				List<ArticleGroup> groups = serviceFactory.getPersistService().find(ArticleGroup.class, groupquery);
				String groupname = "";
				if (groups != null && groups.size() > 0) {
					for (ArticleGroup g : groups) {
						groupname = groupname + g.getName() + ",";
					}
				}
				articleVo.setGroupname(groupname);
				articleVos.add(articleVo);
			}
			Long count = result.getTotalCount();
			page.setEntityCount(count.intValue());
			model.put("articlelist", articleVos);
			model.put("articleListPage", page);
			model.put("categorys", categorys);
			return "/article/articlemanage";
		}
		catch (Exception ex)
		{
			logger.error(ex);
			return returnError(model, ex);
		}
	}

	@RequestMapping(value = "/get/{id}")
	public ModelAndView get(@PathVariable Long id, ModelMap model)
	{
		if (id == null)
			return new ModelAndView(returnError(model, "新闻ID不能为空！"));
		Article article = serviceFactory.getPersistService().get(Article.class, id);
		if (article == null)
			return new ModelAndView(returnError(model, "新闻不存在！"));
		String filename = null;
		String url = null;
		Long groupId = null;

		// 所有分组
		List<ArticleGroup> articleGroups = new ArrayList<ArticleGroup>();
		ArticleGroup articleGroup = new ArticleGroup();
		articleGroup.setId(-1L);
		articleGroup.setName("全部");
		articleGroups.add(articleGroup);
		articleGroups.addAll(serviceFactory.getPersistService().list(ArticleGroup.class));
		// 已选分组
		List<ArticleGroup> articleGroupsSelf = new ArrayList<ArticleGroup>();
		List<ArticleGroupEx> agList = serviceFactory.getArticleService().findUnionArticleById("articleId",
				new Long[] { id }, ArticleGroupEx.class);
		if (agList != null)
		{
			for (ArticleGroupEx articleGroupEx : agList)
			{
				if (articleGroupEx.getGroupId() == -1)
				{
					ArticleGroup articleGroupt = new ArticleGroup();
					articleGroupt.setId(-1L);
					articleGroupt.setName("全部");
					articleGroupsSelf.add(articleGroupt);
				}
				else
				{
					articleGroupsSelf.add(serviceFactory.getPersistService().get(ArticleGroup.class,
							articleGroupEx.getGroupId()));
				}
			}
			List<Attachment> amList = serviceFactory.getArticleService().findUnionArticleById("articleId",
					new Long[] { id }, Attachment.class);
			for (Attachment attachment : amList)
			{
				if (attachment.getType() == AttachmentType.IMAGE)
				{
					filename = attachment.getFilePath();
					url = attachment.getUrl();
					break;
				}
			}
		}
		// 未选分组
		Collection<ArticleGroup> articleGroupDiff = CollectionHelp.findCollectionDiff(articleGroups, articleGroupsSelf);

		Set<ArticleCategory> categorys = serviceFactory.getArticleCategorySerivce().findAllArticleCategorySort(null)
				.getReturnValue();
		ArticleCategory articleCategory = serviceFactory.getPersistService().get(ArticleCategory.class,
				article.getCategory().getId());
		ModelAndView modelAndView = new ModelAndView("/article/detail");
		modelAndView.addObject("filename", filename);
		modelAndView.addObject("url", url);
		modelAndView.addObject("article", article);
		modelAndView.addObject("categorys", categorys);
		modelAndView.addObject("category", articleCategory);
		modelAndView.addObject("groupsSelf", articleGroupsSelf);
		modelAndView.addObject("diffGroups", articleGroupDiff);
		modelAndView.addObject("groupId", groupId);
		return modelAndView;
	}

	@RequestMapping(value = "/preview/{id}")
	public String perView(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id, ModelMap map)
	{
		Article article = serviceFactory.getArticleService().load(id).getReturnValue();
		if (article == null)
			return returnError(map, "新闻不存在！");
		try
		{
			String NEWS_VIEW_URL = serviceFactory.getPersistService().get(SystemConfig.class, "news.view.url")
					.getValue();
			response.sendRedirect(NEWS_VIEW_URL + id);
			return null;
		}
		catch (Exception e)
		{
			logger.error(e);
			return returnError(map, e.getMessage());
		}
	}

	@RequestMapping(value = "/check/{id}")
	@ResponseBody
	public String check(@PathVariable Long id, ModelMap map)
	{
		String flag = null;
		try
		{
			Article article = serviceFactory.getArticleService().get(id).getReturnValue();
			article.setIsAudited(BoolValue.YES);
			article = serviceFactory.getArticleService().modfiy(article).getReturnValue();
			flag = "YES";
		}
		catch (Exception e)
		{
			logger.error(e);
			flag = "NO";
		}
		return flag;
	}

	/*
	 * 查询出栏目的子栏目ID数组（包括自己）
	 */
	public Long[] findCategoryChildrenIds(Long categoryId)
	{
		if (categoryId == null || categoryId == 0L)
			return null;
		List<ArticleCategory> cts = serviceFactory
				.getArticleCategorySerivce()
				.findArticleCategoryPage(null, categoryId, Constant.G_INT_DATA_INVALID, Constant.G_INT_DATA_INVALID,
						null).getReturnValue();
		Long[] cIds = new Long[cts.size() + 1];
		cIds[cts.size()] = categoryId;
		for (int i = 0; i < cts.size(); i++)
			cIds[i] = cts.get(i).getId();
		return cIds;
	}

	/**
	 * 查询评论
	 * @param request
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/discuss")
	public String queryDiscuss(HttpServletRequest request, ModelMap model, String articleId)
	{
		String content = request.getParameter("content");
		String userName = request.getParameter("userName");
		String publishTime_s = request.getParameter("publishTime_s");
		String publishTime_e = request.getParameter("publishTime_e");
		String state = request.getParameter("state");
		String auditor = request.getParameter("auditor");
		String auditTime_s = request.getParameter("auditTime_s");
		String auditTime_e = request.getParameter("auditTime_e");
		// 默认查询未审核
		state = StringHelper.isEmpty(state) ? "NOAUDIT" : state;
		model.put("articleId", articleId);
		model.put("content", content);
		model.put("userName", userName);
		model.put("publishTime_s", publishTime_s);
		model.put("publishTime_e", publishTime_e);
		model.put("state", state);
		model.put("auditor", auditor);
		model.put("auditTime_s", auditTime_s);
		model.put("auditTime_e", auditTime_e);
		// 为空查询所有
		articleId = StringHelper.isEmpty(articleId) ? "-1" : articleId;

		Pagination page = new Pagination(request);
		page.setPageSize(this.getPageSize(request));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date publishDate_s = null;
		Date publishDate_e = null;
		Date auditDate_s = null;
		Date auditDate_e = null;
		if (!StringHelper.isEmpty(publishTime_s))
		{
			try
			{
				publishDate_s = sdf.parse(publishTime_s);
				publishDate_e = sdf.parse(publishTime_e);

				auditDate_s = sdf.parse(auditTime_s);
				auditDate_e = sdf.parse(auditTime_e);
			}
			catch (ParseException e)
			{
				logger.error(e);
			}
		}
		QueryResult<ArticleDiscuss> result = serviceFactory.getArticleService().findDicuss(Long.parseLong(articleId),
				content, userName, publishDate_s, publishDate_e, state, auditor, auditDate_s, auditDate_e,
				page.currentPage, page.pageSize);
		List<ArticleDiscussVo> discussVos = BeanClone.clone(result.getResults(), ArticleDiscussVo.class);
		for (ArticleDiscussVo discussVo : discussVos)
		{
			ServiceResult<Article> articleResult = serviceFactory.getArticleService().get(discussVo.getArticleId());
			Article article = articleResult.getReturnValue();
			if (article != null)
			{
				discussVo.setArticleAuthor(article.getAuthor());
				discussVo.setArticleCategory(article.getCategory().getName());
			}

		}
		Long count = result.getTotalCount();
		page.setEntityCount(count.intValue());
		model.put("discussList", discussVos);
		model.put("discussListPage", page);
		return "/article/discuss";
	}

	/**
	 * 删除评论
	 * @param request
	 * @param ids
	 * @param map
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/discuss/remove")
	public String deleteDiscuss(HttpServletRequest request, Long[] ids, ModelMap map)
	{
		if (ids == null || ids.length <= 0)
		{
			return returnError(map, "要删除的评论ID不能为空！");
		}
		try
		{
			ServiceResult<ArticleDiscuss> result = serviceFactory.getArticleService().batchRemove("id", ids,
					ArticleDiscuss.class);
			return returnSuccess(request, map, result, "/am/discuss");
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return returnError(map, ex);
		}
	}

	/**
	 * 修改评论状态
	 * @param request
	 * @param ids
	 * @param map
	 * @param id
	 * @param type
	 * @return
	 */
	@RequestMapping(value = "/discuss/updateState")
	public String updateState(HttpServletRequest request, Long[] ids, ModelMap map, String type)
	{
		if (ids == null || ids.length <= 0)
		{
			return returnError(map, "要修改状态的评论ID不能为空！");
		}
		try
		{
			List<ArticleDiscuss> list = serviceFactory.getArticleService().findDicuss(ids);
			DiscussState state = DiscussState.valueOf(type);
			Date auditTime = new Date();
			Passport session = getUserSession(request.getSession());
			for (ArticleDiscuss articleDiscuss : list)
			{
				articleDiscuss.setState(state);
				articleDiscuss.setAuditTime(auditTime);
				articleDiscuss.setAuditor(session.getRealName());
				serviceFactory.getPersistService().update(articleDiscuss);
			}
			return returnSuccess(request, map, new ServiceResult<ArticleDiscuss>(), "/am/discuss");
		}
		catch (Exception ex)
		{
			logger.error(ex);
			return returnError(map, ex);
		}
	}
}
